<?php

namespace app\achievement\controller;
use app\common\model\ConfigModel;
use think\Db;
use think\Cache;

class Config extends Base
{


    private $cfg = '';

    public function __construct()
    {
        parent::__construct();
        $this->cfg = new ConfigModel();
    }

    /**
     * [index 配置列表]
     */
    public function index(){

        $key = input('key');
        $map = [];
        if($key&&$key!=="")
        {
            $map['title'] = ['like',"%" . $key . "%"];
        }
        $nowpage = input('get.page') ? input('get.page'):1;
        $limits = 10;// 获取总条数
        $count = $this->cfg->getAllCount($map);//计算总页面
        $allpage = intval(ceil($count / $limits));
        $list = $this->cfg->getAllConfig($map, $nowpage, $limits);

        // 模板赋值
        $this->assign('count', $count); // 总条数
        $this->assign('pageSize', $limits); // 每页条数
        $this->assign('nowpage', $nowpage); //当前页
        $this->assign('allpage', $allpage); //总页数
        $this->assign('val', $key);
        $this->assign('list', $list);
        return $this->fetch();
    }


    /**
     * [add_config 添加配置]
     */
    public function add_config()
    {
        if(request()->isAjax()){

            $param = input('post.');
            $config = new ConfigModel();
            $flag = $this->cfg->insertConfig($param);
            Cache::clear(); 
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }
        return $this->fetch();
    }


    /**
     * [edit_config 编辑配置]
     */
    public function edit_config()
    {
        $config = new ConfigModel();

        if(request()->isAjax()){
            $param = input('post.');
            $flag = $this->cfg->editConfig($param);
            Cache::clear(); 
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }

        $id = input('param.id');
        $info = $config->getOneConfig($id);
        $this->assign('info', $info);
        return $this->fetch();
    }


    /**
     * [del_config 删除配置]
     */
    public function del_config()
    {
        $id = input('param.id');
        $config = new ConfigModel();
        $flag = $this->cfg->delConfig($id);
        Cache::clear(); 
        return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
    }



    /**
     * [user_state 配置状态]
     */
    public function status_config()
    {
        $id = input('param.id');
        $status = Db::name('config')->where(array('id'=>$id))->value('status');//判断当前状态情况
        Cache::clear(); 
        if($status==1)
        {
            $flag = Db::name('config')->where(array('id'=>$id))->setField(['status'=>0]);
            return json(['code' => 1, 'data' => $flag['data'], 'msg' => '已禁止']);
        }
        else
        {
            $flag = Db::name('config')->where(array('id'=>$id))->setField(['status'=>1]);
            return json(['code' => 0, 'data' => $flag['data'], 'msg' => '已开启']);
        }

    }


    /**
     * [获取某个标签的配置参数]
     */
    public function group() {
        $id   = input('id',1);
        $type = config('config_group_list');

        $list = Db::name("Config")->where(array('status'=>1,'group'=>$id))->field('id,name,title,extra,value,remark,type')->order('sort')->select();
        $this->assign('list',$list);
        $this->assign('config_group_list',config('config_group_list'));
        $this->assign('id',$id);
        return $this->fetch();
    }



    /**
     * [批量保存配置]
     */
    public function save($config){
        if($config && is_array($config)){
            $Config = Db::name('Config');
            $res = true;
            foreach ($config as $name => $value) {
                $map = array('name' => $name);
                $Config->where($map)->setField('value', $value);
            }
        }
        Cache::clear(); 
        if($res){
            returnJson(1,"保存成功");
        }
         returnJson(0,"保存失败");
    }


    public function extend () {

        $key = input('key');
        $map = [];
        //$map['closed'] =0;
        if($key&&$key!=="")
        {
        $map['title'] = ['like',"%" . $key . "%"];
        }
        $Nowpage = input('get.page') ? input('get.page'):1;
        $limits = 10;// 获取总条数
        $count = Db::name('extend')->where($map)->count();//计算总页面
        $allpage = intval(ceil($count / $limits));

        $lists = $this->cfg->getAllExt($map, $Nowpage, $limits);
        $this->assign('count',$count);
        $this->assign('Nowpage', $Nowpage); //当前页
        $this->assign('allpage', $allpage); //总页数
        $this->assign('val', $key);
        if(input('get.page'))
        {
            return json($lists);
        }

        return $this->fetch();
    }

    /**
     * 添加新的配置项
     */
    public function add_ext() {

        if(request()->isPost()){
            $param      = input('post.');
            $flag       = $this->cfg->insertExt($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }
    }

    /**
     * 删除配置
     */
    public function del_ext () {

        $id         = input('param.id');
        $flag       = Db::name('extend')->where('id',$id)->delete();
        $msg        = $flag ? '删除成功' : '删除失败';
        return json(['code'=>1,'msg'=>$msg,'data'=>'']);

    }

    /**
     * 编辑扩展配置
     */
    public function edit_ext () {

        if(request()->isPost()){
            $param = input('post.');
            $value = array_combine($param['value'], $param['val']);
            unset($param['val']);
            $param['value'] = json_encode($value);
            $flag = $this->cfg->editExt($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }

        $id = input('param.id');
        $ext = $this->cfg->getOneEXT($id);
        $exts = json_decode($ext['value'],true);

     /*   if ( is_array($exts) ){
            while(list($key, $val) = each($exts)){

            }
         }*/
        $this->assign('conf',$ext);
        $this->assign('confs',$exts);
        return $this->fetch();
    }

    /**
     * 城市TDS列表
     * @author ligang
     * @return mixed|\think\response\Json
     * @date 2018/12/28 16:41
     */
    public function settingTdsList()
    {
        $row = input('row') ?? config('pagesize');
        $page = input('page') ?? 1;
        $key = input('key') ?? '';

        $where = [];
        if (!empty($key)){
            $where['p.area_name|c.area_name|a.area_name'] = ['LIKE','%'.trim($key).'%'];
        }
        $join = [
            ['rq_areas p','rq_address_tds.p_code = p.id','LEFT'],
            ['rq_areas c','rq_address_tds.c_code = c.id','LEFT'],
            ['rq_areas a','rq_address_tds.a_code = a.id','LEFT'],
        ];
        $field = '
            p.area_name as p_name,
            c.area_name as c_name,
            a.area_name as a_name,
            rq_address_tds.tds,
            rq_address_tds.id
        ';
        $result = db('address_tds')->where($where)->field($field)->join($join)->page($page,$row)->select();
        $count = db('address_tds')->join($join)->count();
        $total_page = ceil($count/$row);
        // 模板赋值
        $this->assign('Nowpage', $page); //当前页
        $this->assign('allpage', $total_page); //总页数
        $this->assign('count', $count);
//        $this->assign('tlist', $tlist);
        $this->assign('vals', $key);
        if (input('get.page')) {
            return json($result);
        }
        return $this->fetch('config/settingTdsList');
    }

    /**
     * 添加城市TDS
     * @author ligang
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @date 2018/12/28 16:41
     */
    public function addTds()
    {
        if ($this->request->isPost()){
            $p_code = input('p_name') ?? '';
            $c_code = input('c_name') ?? '';
            $a_code = input('a_name') ?? '';
            $tds = input('tds') ?? '';
            if (empty($p_code)){
                return json(['code'=>0,'msg'=>'请选择省份']);
            }
            if (empty($c_code)){
                return json(['code'=>0,'msg'=>'请选择市级']);
            }
            if (empty($a_code)){
                return json(['code'=>0,'msg'=>'请选择区县']);
            }
            if (empty($tds)){
                return json(['code'=>0,'msg'=>'请输入TDS']);
            }
            $where = [
                'p_code'=>$p_code,
                'c_code'=>$c_code,
                'a_code'=>$a_code
            ];
            $result = Db::table('rq_address_tds')->where($where)->find();
            if (!empty($result)){
                Db::table('rq_address_tds')->where(['id'=>$result['id']])->update(['tds'=>trim($tds)]);
                return json(['code'=>1,'msg'=>'已存在该城市TDS，更新成功']);
            }
            $data = [
                'p_code'=>$p_code,
                'c_code'=>$c_code,
                'a_code'=>$a_code,
                'tds'=>trim($tds)
            ];
            Db::table('rq_address_tds')->insert($data);
            return json(['code'=>1,'msg'=>'添加成功']);
        }
        $p_name = Db::table('rq_areas')->where(['parent_id'=>0])->select();
        $this->assign('p_name',$p_name);
        return $this->fetch('config/addTds');
    }

    /**
     * 编辑城市TDS
     * @author ligang
     * @return bool|mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @date 2018/12/28 16:41
     */
    public function editTds()
    {
        $id = input('id') ?? '';
        if (empty($id)){
            $this->error('请选择城市');
            return false;
        }
        $result = Db::table('rq_address_tds')->where(['id'=>$id])->find();
        if (empty($result)){
            $this->error('信息不存在');
            return false;
        }
        if ($this->request->isPost()){
            $p_code = input('p_name') ?? '';
            $c_code = input('c_name') ?? '';
            $a_code = input('a_name') ?? '';
            $tds = input('tds') ?? '';
            if (empty($p_code)){
                return json(['code'=>0,'msg'=>'请选择省份']);
            }
            if (empty($c_code)){
                return json(['code'=>0,'msg'=>'请选择市级']);
            }
            if (empty($a_code)){
                return json(['code'=>0,'msg'=>'请选择区县']);
            }
            if (empty($tds)){
                return json(['code'=>0,'msg'=>'请输入TDS']);
            }
            $data = [
                'id'=>$id,
                'p_code'=>$p_code,
                'c_code'=>$c_code,
                'a_code'=>$a_code,
                'tds'=>trim($tds)
            ];
            Db::table('rq_address_tds')->update($data);
            return json(['code'=>1,'msg'=>'编辑成功']);
        }
        $p_name = Db::table('rq_areas')->where(['parent_id'=>0])->select();
        $c_name = Db::table('rq_areas')->where(['parent_id'=>$result['p_code']])->select();
        $a_name = Db::table('rq_areas')->where(['parent_id'=>$result['c_code']])->select();
        $this->assign('p_name',$p_name);
        $this->assign('c_name',$c_name);
        $this->assign('a_name',$a_name);
        $this->assign('data',$result);
        return $this->fetch('config/editTds');
    }

    public function getAddress()
    {
        $id = input('id') ?? '';
        if (empty($id)){
            return json(['code'=>0,'msg'=>'请选择上级']);
        }
        $c_name = Db::table('rq_areas')->where(['parent_id'=>$id])->select();
        return json(['code'=>1,'msg'=>'获取成功','data'=>$c_name]);
    }
}